<?php

/**
 * 安心站长axzz.cn，一个追求技术创造者。让网站、小程序、APP牛起来……
 *
 * cighsen02 3651872575
 * 
 * Create at: 2024.05.01
 * Update at: 2025.08.09
*/

namespace Twoir\Service\Member;

use Exception;
use Twoir\Service\BaseInfo;
use Twoir\Service\BaseMember;
use Twoir\System\Model\EnewsFava;

/**
 * 功能小组件 点赞
 */
class Widgets extends BaseMember
{
    // 模型
    protected ?BaseInfo $info;

    /**
     * 收藏增加
     *
     * @param array $add
     * @return array
     *
     * @throws Exception
    */
    public function setFava(array $add): array
    {
        global $level_r;

        $add    = $this->paramFilter($add);
        $groupid= $this->user['groupid'];

        if (!isset($add['classid']) || !isset($add['id'])) throw new Exception('参数错误', 9200);

        if ($this->info) {

            $this->info->setClassId($add['classid']);
        }
        else {

            $this->info = new BaseInfo($add['classid']);
        }

        if (empty($info = $this->info->getOne(['classid' => $add['classid'], 'id' => $add['id']], ['ismember','userid'])) || !isset($info['userid'])) {

            throw new Exception('内容不存在', 3200);
        }

        if ($info['userid'] == $this->user['userid'] && 1 == $info['ismember']) throw new Exception('不需要收藏自己的文章', 4200);

        // 已收藏
        if (EnewsFava::getCount(['classid' => $add['classid'], 'id' => $add['id'], 'userid' => $this->user['userid']]) > 0) {

            throw new Exception('已经收藏此文章', 5200);
        }

        if (isset($level_r[$groupid]['favanum']) && $level_r[$groupid]['favanum'] <= EnewsFava::getCount(['userid' => $this->user['userid']])) {

            throw new Exception('已经超过最大收藏数了', 6200);
        }

        // 增加收藏记录
        $data = [
            'classid'   => $add['classid'],
            'id'        => $add['id'],
            'userid'    => $this->user['userid'],
            'username'  => $this->user['username'],
            'cid'       => $add['cid'] ?? 0, //默认
            'favatime'  => date("Y-m-d H:i:s")
        ];

        $favaid = EnewsFava::insert($data);

        return $favaid ?  [
            'favaid' => $favaid
        ] + $data : [];
    }
}
